<?php
namespace app\extensions\qiniu;

use Exception;
use Qiniu_RS_PutPolicy;

require_once dirname(__FILE__) . '/lib/rs.php';
require_once dirname(__FILE__) . '/lib/auth_digest.php';
require_once dirname(__FILE__) . '/lib/auth_digest.php';
require_once dirname(__FILE__) . '/lib/io.php';

class Qiniu
{
    private $_ak;
    private $_sk;
    private $_bucket;
    private $url;

    function __construct($_ak, $_sk, $_bucket, $url)
    {
        $this->_ak = $_ak;
        $this->_bucket = $_bucket;
        $this->_sk = $_sk;
        $this->url = $url;
    }

    /**
     * 设置路径
     * @param $key
     * @param null $returnUrl
     * @param null $returnBody
     * @return string
     */
    public function getSign($preKey = '', $returnUrl = null, $returnBody = null)
    {
        Qiniu_SetKeys($this->_ak, $this->_sk);
        $putPolicy = new Qiniu_RS_PutPolicy($this->_bucket);
        $putPolicy->Expires = 60 * 30;

        if ($returnUrl !== null)
            $putPolicy->ReturnUrl = $returnUrl;

        if ($returnBody !== null) {
            $putPolicy->ReturnBody = json_encode($returnBody);
        }

        $upToken = $putPolicy->Token(null);

        return $upToken;

    }

    public function saveFile($token, $filename, $file, $ext = null)
    {
        list($ret, $err) = Qiniu_PutFile($token, $filename, $file, $ext);

        if (!empty($err)) throw new Exception(print_r($err, 1));

        return $ret;
    }

    public function saveContent($token, $filename, $body, $ext = null)
    {
        list($ret, $err) = Qiniu_Put($token, $filename, $body, $ext);
        if (!empty($err)) throw new Exception(print_r($err, 1));
        return $ret;
    }

    public function getUrl($key = '')
    {
        return empty($key) ? $this->url : $this->url . '/' . $key;
    }
}
